﻿#include "ModbusRtuServer.h"
#pragma execution_character_set("utf-8")
ModbusRtuServer::ModbusRtuServer(QObject *parent)
    : PLCServerBase{parent}
{
    mServer = new QModbusRtuSerialSlave(this);
    connect(mServer, &QModbusServer::errorOccurred, this, [&](QModbusDevice::Error error){
        emit sigErrOccur(mConfig.name + mServer->errorString());
    });
    connect(mServer, &QModbusServer::stateChanged, this, [&](QModbusDevice::State state){
        if(state == QModbusDevice::ConnectedState){
            setServerState(CS_Connected);
        } else  if(state == QModbusDevice::UnconnectedState){
            setServerState(CS_UnConnected);
        }
    });
    connect(mServer, &QModbusServer::dataWritten, this, &ModbusRtuServer::readData);
}
void ModbusRtuServer::initCom()
{
    if (!mServer) {
        emit sigErrOccur(tr("Could not create Modbus server."));
    } else {
        if(mServer->state() == QModbusDevice::ConnectedState){
            mServer->disconnectDevice();
        }
        QModbusDataUnitMap reg;
        coilDataPre =  { QModbusDataUnit::Coils, 0, mConfig.addrCount };
        holdDataPre =  { QModbusDataUnit::DiscreteInputs, 0, mConfig.addrCount };
        discreDataPre =  { QModbusDataUnit::HoldingRegisters, 0, mConfig.addrCount};
        inputDataPre =  { QModbusDataUnit::InputRegisters, 0, mConfig.addrCount };
        reg.insert(QModbusDataUnit::Coils, coilDataPre);
        reg.insert(QModbusDataUnit::DiscreteInputs, discreDataPre);
        reg.insert(QModbusDataUnit::HoldingRegisters, holdDataPre);
        reg.insert(QModbusDataUnit::InputRegisters, inputDataPre);

        mServer->setMap(reg);

        //connect plc
        mServer->setConnectionParameter(QModbusDevice::SerialPortNameParameter,mConfig.serial.comId);
        mServer->setConnectionParameter(QModbusDevice::SerialParityParameter,mConfig.serial.parity);
        mServer->setConnectionParameter(QModbusDevice::SerialBaudRateParameter,mConfig.serial.baudRate);
        mServer->setConnectionParameter(QModbusDevice::SerialDataBitsParameter,mConfig.serial.dataBits);
        mServer->setConnectionParameter(QModbusDevice::SerialStopBitsParameter,mConfig.serial.stopBits);
        mServer->setServerAddress(mConfig.serverID);

        if (!mServer->connectDevice()) {
            emit sigMsg(tr("<font color=\'red\'>服务端连接失败 </font>") + mServer->errorString());
        } else {
            setServerState(CS_Connected);
            emit sigMsg(tr("<font color=\'green\'>服务端连接成功 </font>"));
        }
    }
}
